package com.example.uploadhealth.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.uploadhealth.domain.ResponseResult;
import com.example.uploadhealth.domain.eneity.HealthImg;
import com.example.uploadhealth.domain.eneity.LoginUser;
import com.example.uploadhealth.domain.eneity.User;
import com.example.uploadhealth.domain.vo.HealthImgVo;
import com.example.uploadhealth.domain.vo.PageVo;
import com.example.uploadhealth.enums.AppHttpCodeEnum;
import com.example.uploadhealth.exception.SystemException;
import com.example.uploadhealth.mapper.HealthImgMapper;
import com.example.uploadhealth.mapper.UserMapper;
import com.example.uploadhealth.service.HealthImgService;
import com.example.uploadhealth.utils.BeanCopyUtils;
import com.example.uploadhealth.utils.PathUtils;
import com.example.uploadhealth.utils.SecurityUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * (HealthImg)表服务实现类
 *
 * @author makejava
 * @since 2022-03-15 10:18:36
 */

@Data
@ConfigurationProperties(prefix = "oss")
@Service("healthImgService")
public class HealthImgServiceImpl extends ServiceImpl<HealthImgMapper, HealthImg> implements HealthImgService {
    private String accessKey;
    private String secretKey;
    private String bucket;
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult upLoadHealth(MultipartFile img) {
        String url = uploadOss(img);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(loginUser);
        System.out.println(url);
        HealthImg healthImg = new HealthImg();
        healthImg.setHealthImg(url);
        healthImg.setCreateBy(loginUser.getUser().getId());
        save(healthImg);
        return ResponseResult.okResult(url);
    }

    @Override
    public ResponseResult getUserHealthImg(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getType, 1);
        List<User> usersList = userMapper.selectList(queryWrapper);

        LambdaQueryWrapper<HealthImg> queryWrapperImg = new LambdaQueryWrapper<>();
        queryWrapperImg.eq(HealthImg::getImgtype,1);//查找图片类型为1的
        IPage<HealthImg> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapperImg);
        List<HealthImg> page1 = page.getRecords();
        List<HealthImgVo> healthImgVos = BeanCopyUtils.copyBeanList(page1, HealthImgVo.class);
        System.out.println(healthImgVos);

        usersList.forEach((item) -> {
            for (HealthImgVo healthImgVo : healthImgVos) {
                System.out.println(item.getId() + healthImgVo.getCreateBy());
                if (Objects.equals(item.getId(), healthImgVo.getCreateBy())) {
                    System.out.println("1111111111111");
                    healthImgVo.setNickName(item.getNickName());
                    healthImgVo.setClassName(item.getClassName());
                    healthImgVo.setPhonenumber(item.getPhonenumber());
                }
            }
        });
        System.out.println(healthImgVos);
        PageVo pageVO = new PageVo(healthImgVos, page.getTotal());
        return ResponseResult.okResult(pageVO);
    }

    @Override
    public ResponseResult getUserHealthByNickName(String nickName) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, nickName);
        User user = userMapper.selectOne(queryWrapper);
        Long id = null;
        System.out.println(user);
        if (!Objects.isNull(user)) {
            id = user.getId();
        } else {
            throw new SystemException(AppHttpCodeEnum.USERNOEXIT);
        }
        System.out.println(id);
        LambdaQueryWrapper<HealthImg> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(HealthImg::getCreateBy, id);
        List<HealthImg> list = list(queryWrapper1);
        List<HealthImgVo> healthImgVos = BeanCopyUtils.copyBeanList(list, HealthImgVo.class);
        for (HealthImgVo healthImgVo : healthImgVos) {
            System.out.println("1111111111111");
            healthImgVo.setNickName(user.getNickName());
            healthImgVo.setClassName(user.getClassName());
            healthImgVo.setPhonenumber(user.getPhonenumber());
        }
        PageVo pageVO = new PageVo(healthImgVos, (long) healthImgVos.size());
        return ResponseResult.okResult(pageVO);
    }

    @Override
    public ResponseResult getUserTravelImg(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getType, 1);
        List<User> usersList = userMapper.selectList(queryWrapper);

        LambdaQueryWrapper<HealthImg> queryWrapperImg = new LambdaQueryWrapper<>();
        queryWrapperImg.eq(HealthImg::getImgtype,2);//查找图片类型为1的
        IPage<HealthImg> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapperImg);
        List<HealthImg> page1 = page.getRecords();
        List<HealthImgVo> healthImgVos = BeanCopyUtils.copyBeanList(page1, HealthImgVo.class);
        System.out.println(healthImgVos);

        usersList.forEach((item) -> {
            for (HealthImgVo healthImgVo : healthImgVos) {
                System.out.println(item.getId() + healthImgVo.getCreateBy());
                if (Objects.equals(item.getId(), healthImgVo.getCreateBy())) {
                    System.out.println("1111111111111");
                    healthImgVo.setNickName(item.getNickName());
                    healthImgVo.setClassName(item.getClassName());
                    healthImgVo.setPhonenumber(item.getPhonenumber());
                }
            }
        });
        System.out.println(healthImgVos);
        PageVo pageVO = new PageVo(healthImgVos, page.getTotal());
        return ResponseResult.okResult(pageVO);
    }

    private String uploadOss(MultipartFile img) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
//        String accessKey = "KxVsyyd2KbiG2MGByZmkZ9fDQmGNn4cbtxtzXl-h";
//        String secretKey = "d3s3JZe0I6Sglm_lTRiyZucmp7CMYTBl_9eDRDjV";
//        String bucket = "noobzjp";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            System.out.println(img);
            key = PathUtils.generateFilePath(String.valueOf(img.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            InputStream inputStream = img.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://" + "r8mscfjlu.hb-bkt.clouddn.com/" + key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "666";
    }
}


